package com.rkc.config;

import feign.RequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author `RKC`
 * @date 2021/11/12 15:48
 */
@Configuration
public class RequestAttributeConfiguration {

    /**
     * feign调用token丢失解决方式，新增拦截器，请求在服务间转换时，拦截原request，将其header或者parameter
     * 重新设置到新的request
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String token = request.getHeader("token");
                if (StringUtils.isBlank(token)) {
                    token = request.getParameter("token");
                }
                if (!StringUtils.isBlank(token)) {
                    template.header("token", token);
                }
            }
        };
    }
}
